<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="AddRolesDialog = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="RolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              :class="[
                i1 == 0 ? 'dbtop' : '',
                'adpadding',
                'vcenter',
                'dbbottom',
              ]"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[i2 == 0 ? '' : 'dbtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="getRolesByID(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="getRightList(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddRolesDialog"
      width="50%"
      @close="AddRolesDialogClose"
    >
      <el-form
        ref="RolesRef"
        :model="rolesForm"
        :rules="rules"
        label-width="80px"
      >
        <!-- 添加角色表单区域 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="AddRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色弹出框  -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialog"
      width="30%"
      @close="getRolesInfoClose"
    >
      <el-form
        ref="editRolesRef"
        :model="getRolesInfo"
        :rules="rules"
        label-width="80px"
      >
        <!-- 修改角色表单区域 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="getRolesInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="getRolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRolesDialogVisible"
      width="50%"
      @close="SetRolesDialogClose"
    >
      <el-tree
        :data="rightsList"
        :props="SelectProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer">
        <el-button @click="SetRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRighs"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      RolesList: [],
      AddRolesDialog: false, //弹出添加角色对话框
      editRolesDialog: false, //弹出修改角色对话框
      getRolesInfo: {}, //查询到的角色信息
      rolesForm: {
        //添加角色所绑定的数据源
        roleName: "",
        roleDesc: "",
      },
      SetRolesDialogVisible: false, //控制分配角色对话框的显示与隐藏
      rightsList: [], //所有权限列表数据（树状）
      SelectProps: {
        //需要渲染的数据
        children: "children",
        label: "authName",
      },
      defKeys:[],//默认选择节点id值数组
      roleId:'',//即将分配权限角色id
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,

            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],

        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 5,
            max: 20,

            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },

  created() {
    this.getRolesList();
  },

  methods: {
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status == 200) {
        this.RolesList = res.data;
        this.$message.success("获取角色列表成功");
      } else {
        this.$message.error("获取角色列表失败");
      }
    },

    //点击确认后预校验添加角色
    AddRole() {
      //预校验
      this.$refs.RolesRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("roles", this.rolesForm);
          if (res.meta.status == 201) {
            this.$message.success("添加用户成功");
            this.AddRolesDialog = false;
            this.getRolesList();
          } else {
            this.$message.error("添加用户失败");
          }
        } else {
          return;
        }
      });
    },

    //添加角色对话框关闭后重置对话框
    AddRolesDialogClose() {
      this.$refs.RolesRef.resetFields();
    },

    //通过ID查询用户信息
    async getRolesByID(id) {
      this.editRolesDialog = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status == 200) {
        this.getRolesInfo = res.data;
        this.$message.success("查询角色数据成功");
      }
      //    console.log(res);
    },

    //修改窗口关闭后重置表单
    getRolesInfoClose() {
      this.$refs.editRolesRef.resetFields();
    },

    //修改后预校验
    editRoles() {
      this.$refs.editRolesRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "roles/" + this.getRolesInfo.roleId,
            {
              roleName: this.getRolesInfo.roleName,
              roleDesc: this.getRolesInfo.roleDesc,
            }
          );
          //   console.log(res)
          if (res.meta.status == 200) {
            this.$message.success("修改角色信息成功");
            this.editRolesDialog = false; //关闭窗口
            this.getRolesList(); //查询获取数据
          } else {
            this.$message.error("修改角色信息失败");
          }
        } else {
          return;
        }
      });
    },

    //删除角色
    async deleteRoles(id) {
      const val = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (val == "confirm") {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status == 200) {
          this.$message.success("删除角色成功");
          this.getRolesList();
        } else {
          this.$message.error("删除角色失败");
        }
      } else {
        this.$message.info("已取消删除");
      }
    },

    //删除角色权限
    async removeRightsById(role, rightid) {
      const val = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (val == "confirm") {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightid}`
        );
        if (res.meta.status == 200) {
          this.$message.success("成功删除权限");
          role.children = res.data;
        }
      } else {
        this.$message.info("已取消删除");
      }
    },

    //获取所有权限列表
    async getRightList(role) {
      this.roleId=role.id
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status == 200) {
        this.rightsList = res.data;
        this.getLeafKeys(role,this.defKeys)//获取三级节点id
        this.SetRolesDialogVisible = true;//打开窗口
      } else {
        this.$message.error("获取权限列表失败");
      }
    },
    //通过递归的形式，获取角色下所有三级节点的id,并保存到数组defKeys中
    getLeafKeys(node,arr){
      //如果当前节点node不包含children属性，那么他就是三级节点
      if(!node.children){
        return arr.push(node.id)
      }

      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
        // console.log(item);
      })
      
    },

    //监听分配权限对话的关闭事件
    SetRolesDialogClose(){
      this.defKeys=[]//需要重新赋值，不然下次打开会有上次打开的权限
    },

    async allotRighs(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr=keys.join(',')
      const{ data:res }=await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })
      if(res.meta.status==200){
        this.$message.success('分配权限成功')
        this.getRolesList()//刷新列表
        this.SetRolesDialogVisible=false//隐藏对话框

      }else{
        this.$message.error('分配权限失败')
      }
    }

  },
};
</script>

<style lang="less" scoped>
.adpadding {
  margin: 0 30px;
}

.el-tag {
  margin: 10px 10px 0 0;
}

.vcenter {
  display: flex;
  align-items: center;
}

.dbbottom {
  border-bottom: 1px solid #ebeef5;
}

.dbtop {
  border-top: 1px solid #ebeef5;
}
</style>